<?php

function route($map, Request $request, Response $response) {
	$uri = $request->uri();
	$full_url = $request->url();

	$match = '';
	foreach ($map as $rule => $ctl_name) {
		$req_str = strpos($rule, 'http') === 0 ? $full_url : $uri;
		$rule = str_replace(array('\\{', '\\}'), array('{', '}'), preg_quote($rule, '/'));
		$reg_exp = preg_replace('/\{([^\{\}]+)\}/', '(?<$1>[\.\-\_0-9a-zA-Z]+)', $rule);
		if (preg_match('/^' . $reg_exp . '/', $req_str, $m)) {
			$match = $m[0];
			foreach ($m as $key => $value) {
				if (!is_numeric($key)) $request->$key = $value;
			}
			break;
		} else {
			//reset $ctl_name
			$ctl_name = '';
		}
	}

	if (!$ctl_name) {
		return array('', '');
	}

  $path = ($match == '/' ? substr($req_str, 1) : str_replace($match, '', $req_str));

	if (preg_match('/^(?<method>[\-\_0-9a-zA-Z]+)/', $path, $m)
		&& is_callable(array($ctl_name, $m['method']))
	) {
		$method = $m['method'];
	} elseif (is_callable(array($ctl_name, 'index'))) {
		$method = 'index';
	} else {
		return array('', '');
	}

	return array($ctl_name, $method);
}
